package com.diyunapp.xilinapp.me;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.main.MainActivity;
import com.diyunapp.xilinapp.selfdefine.StatusBarFragmentActivity;
import com.diyunapp.xilinapp.utils.CodeCountDown;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.Bind;
import butterknife.BindColor;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginPassActivity extends StatusBarFragmentActivity {

    @Bind(R.id.go_back)
    ImageView goBack;
    @Bind(R.id.Spinner01)
    Spinner Spinner01;
    @Bind(R.id.lin_spinner)
    LinearLayout linSpinner;
    @Bind(R.id.recharge_money_et)
    EditText rechargeMoneyEt;
    @Bind(R.id.getCode_tv)
    TextView getCodeTv;
    @Bind(R.id.sure_to_recharge)
    TextView sureToRecharge;
    @BindColor(R.color.colorDarkTopBar)
    int pressColor;
    @BindColor(R.color.colorText0)
    int unpressColor;
    private ArrayAdapter<String> adapter;
    private String member_id;
    private View headView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_pass);
        ButterKnife.bind(this);
        headView = findViewById(R.id.lgp_menubar_inc);
        super.MenuWidget(headView);
        SharedPreferences userinfo=getSharedPreferences("user_info",MODE_PRIVATE);
        member_id=userinfo.getString("member_id","");
        getBindData(member_id);

    }
    @OnClick({R.id.go_back, R.id.getCode_tv, R.id.sure_to_recharge})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.go_back:
                finish();
                break;
            case R.id.getCode_tv:
                getCodeTv.setClickable(false);
                getCodeTv.setTextColor(unpressColor);
                CodeCountDown.with(LoginPassActivity.this).into(getCodeTv);
                String str=Spinner01.getSelectedItem().toString();
                if (str.indexOf(".com")!=-1) {
                    getCode("email");
                } else  {
                    getCode("mobile");
                }
                break;
            case R.id.sure_to_recharge:
                if(Spinner01.getSelectedItem().toString()==""){
                    Toast.makeText(this,"请输入手机号",Toast.LENGTH_SHORT).show();
                }
                else if(rechargeMoneyEt.getText().toString().trim()==""){
                    Toast.makeText(this,"请输入验证码",Toast.LENGTH_SHORT).show();
                }
                else{
                    sureCode();
                }
                break;
        }
    }
    private void sureCode() {
        String code=rechargeMoneyEt.getText().toString().trim();
        String url=""+MainActivity.url+"act=goods&op=auth&auth_code="+code+"&member_id="+ MainActivity.myLogin.getMemberid()+"";
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String resultinfo = responseInfo.result;
//                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int code = resultObject.optInt("code");
//                            toast(String.valueOf(result));
                            if (code==200) {

                                toast("验证成功");
                                Intent setInt = new Intent(LoginPassActivity.this, LoginPassNextActivity.class);
                                startActivityForResult(setInt, 1);
                            } else {
                                String data= resultObject.optString("data");
                                toast(data);

                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            toast("查询失败");
                            e.printStackTrace();

                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        toast("请求失败");

                    }
                });
    }

    public void getCode(String type){
        String str=Spinner01.getSelectedItem().toString();
        String member_type = null;
        if(type.equals("email")||type=="email"){
            member_type="member_email";
        }else if(type.equals("mobile")||type=="mobile"){
            member_type="member_mobile";
        }
        String url=""+MainActivity.url+"act=goods&op=send_auth_code&type="+type+"&member_id="+MainActivity.myLogin.getMemberid()+"&"+member_type+"="+str+"";
        Log.i("zhangxiaoxidebug", "resultinfo=" + url);

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String resultinfo = responseInfo.result;
//                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            String state = resultObject.optString("state");
//                            toast(String.valueOf(result));
                            if (state.equals("true")) {
                                String msg = resultObject.optString("msg");
                                toast(msg);
                            } else {
                                toast("发送失败");
                                getCodeTv.setClickable(true);
                                getCodeTv.setTextColor(pressColor);

                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            toast("查询失败");
                            e.printStackTrace();

                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        toast("请求失败");

                    }
                });
    }
    private void getBindData(String id) {
        String url=""+MainActivity.url+"act=goods&op=find_mobile_email&member_id="+MainActivity.myLogin.getMemberid()+"";
//        String url = "http://www.xilingou.com/mobile/index.php?act=goods&op=find_mobile_email&member_id="+id+"";
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String resultinfo = responseInfo.result;
//                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.optInt("code");
//                            toast(String.valueOf(result));
                            if (result == 200) {
                                JSONObject recordObject = resultObject.optJSONObject("data");
                                String member_email = recordObject.optString("member_email");
                                String member_mobile = recordObject.optString("member_mobile");
                                int member_email_bind = recordObject.optInt("member_email_bind");
                                int member_mobile_bind = recordObject.optInt("member_mobile_bind");
                                String[] m = new String[0];
                                if (member_email_bind == 1&&member_mobile_bind==0) {
                                    m = new String[]{member_email};
                                }else if(member_mobile_bind==1&&member_email_bind == 0){
                                    m = new String[]{member_mobile};
                                }else if(member_email_bind==1&&member_mobile_bind==1){
                                    m = new String[]{member_email,member_mobile};
                                }
                                dropDown(m);

                            } else {
                                toast("当前暂无数据");
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            toast("查询失败");
                            e.printStackTrace();

                        }
                    }
                    @Override
                    public void onFailure(HttpException error, String msg) {
                        toast("请求失败");
                    }
                });
    }
    public void dropDown(String[] m) {
        SpinnerAdapter adapter = new SpinnerAdapter(this,
                android.R.layout.simple_spinner_item, m);
        Spinner01.setAdapter(adapter);
//        //将可选内容与ArrayAdapter连接起来
//        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, m);
//        //设置下拉列表的风格
//        adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
//        //将adapter 添加到spinner中
//        Spinner01.setAdapter(adapter);
        //添加事件Spinner事件监听
        Spinner01.setOnItemSelectedListener(new SpinnerSelectedListener());
        //设置默认值
        Spinner01.setVisibility(View.VISIBLE);

    }
    private class SpinnerAdapter extends ArrayAdapter<String> {
        Context context;
        String[] items = new String[] {};

        public SpinnerAdapter(final Context context,
                              final int textViewResourceId, final String[] objects) {
            super(context, textViewResourceId, objects);
            this.items = objects;
            this.context = context;
        }

        @Override
        public View getDropDownView(int position, View convertView,
                                    ViewGroup parent) {

            if (convertView == null) {
                LayoutInflater inflater = LayoutInflater.from(context);
                convertView = inflater.inflate(
                        android.R.layout.simple_spinner_item, parent, false);
            }

            TextView tv = (TextView) convertView
                    .findViewById(android.R.id.text1);
            tv.setText(items[position]);
            tv.setGravity(Gravity.CENTER);
            tv.setPadding(16,40,16,40);
            tv.setTextColor(Color.GRAY);
            tv.setTextSize(14);
            return convertView;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater inflater = LayoutInflater.from(context);
                convertView = inflater.inflate(
                        android.R.layout.simple_spinner_item, parent, false);
            }

            // android.R.id.text1 is default text view in resource of the android.
            // android.R.layout.simple_spinner_item is default layout in resources of android.

            TextView tv = (TextView) convertView
                    .findViewById(android.R.id.text1);
            tv.setText(items[position]);
            tv.setGravity(Gravity.LEFT);
            tv.setTextColor(Color.GRAY);
            tv.setTextSize(14);
            return convertView;
        }
    }
    //使用数组形式操作
    class SpinnerSelectedListener implements AdapterView.OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
                                   long arg3) {
            String str=Spinner01.getSelectedItem().toString();
            if (str.indexOf(".com")!=-1) {


            } else if (Spinner01.getSelectedItem().toString() == "手机147****6234") {

            }
        }

        public void onNothingSelected(AdapterView<?> arg0) {
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {


        //用户登录成功后，退回我的页面，并查询更新账户信息
        if (requestCode == 1) {
            if (resultCode == 1) {
                finish();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
